﻿using Chat.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;

namespace Chat.Server
{
    internal class BroadCast
    {

        public static void PushMessage(string msg, string uName, bool flag, Dictionary<string, Socket> client)
        {
            //为每个客户端发送信息
            foreach (var item in client)
            {
                Socket brdcastSocket = (Socket) item.Value;
                string msgTemp = null;
                byte[] castBytes=new byte[4096];
                //是否添加 uName
                if (flag)
                {
                    msgTemp = EncryptionAndDecryption.TripleDESDecrypting(
                        $"{uName}:{msg}\t\t{DateTime.Now.ToString()}");
                    castBytes = Encoding.UTF8.GetBytes(msgTemp);
                }
                else
                {
                    msgTemp= EncryptionAndDecryption.TripleDESDecrypting(
                        $"{msg}\t\t{DateTime.Now.ToString()}");
                    castBytes = Encoding.UTF8.GetBytes(msgTemp);
                }

                try
                {
                    brdcastSocket.Send(castBytes);
                }
                catch (Exception ex)
                {
                    brdcastSocket.Close();
                    brdcastSocket = null;
                    File.AppendAllText($"{AppDomain.CurrentDomain.BaseDirectory}Exception.txt", ex.Message);
                    continue;
                }
            }
        }
    }
}